﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;


namespace socketclient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        /// <summary>
        /// 创建客户端
        /// </summary>
        Socket client;
        private void button1_Click(object sender, EventArgs e)
        {
            ///创建客户端
            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            ///IP地址
            IPAddress ip = IPAddress.Parse(textBox1.Text);
            ///端口号
            IPEndPoint endPoint = new IPEndPoint(ip, int.Parse(textBox2.Text));
            ///建立与服务器的远程连接
            client.Connect(endPoint);
            ///线程问题
            Thread thread = new Thread(ReciveMsg);
            thread.IsBackground = true;
            thread.Start(client);
        }

        /// <summary>
        /// 客户端接收到服务器发送的消息
        /// </summary>
        /// <param name="o">客户端</param>
        void ReciveMsg(object o)
        {
            Socket client = o as Socket;
            while (true)
            {
                try
                {
                    ///定义客户端接收到的信息大小
                    byte[] arrList = new byte[1024 * 1024];
                    ///接收到的信息大小(所占字节数)
                    int length = client.Receive(arrList);
                    string msg = DateTime.Now + Encoding.UTF8.GetString(arrList, 0, length);
                    listBox1.Items.Add(msg);
                }
                catch (Exception)
                {
                    ///关闭客户端
                    client.Close();
                }

            }
        }

        /// <summary>
        /// 客户端发送消息给服务端
        /// </summary>
        private void button2_Click(object sender, EventArgs e)
        {
            if (textBox3.Text != "")
            {
                SendMsg(textBox3.Text);
            }
        }

        /// <summary>
        /// 客户端发送消息，服务端接收到
        /// </summary>
        void SendMsg(string str)
        {
            byte[] arrMsg = Encoding.UTF8.GetBytes(str);
            client.Send(arrMsg);
        }
    }

}
